package com.asohofrucol.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.asohofrucol.dao.FormFieldDataDao;
import com.asohofrucol.dao.FormFieldInputAnswerDao;
import com.asohofrucol.dao.FormFieldInputDao;
import com.asohofrucol.dto.GenericFieldDTO;
import com.asohofrucol.dto.util.FormFieldInputHelper;
import com.asohofrucol.model.FormFieldData;
import com.asohofrucol.model.FormFieldInput;
import com.asohofrucol.model.FormFieldInputAnswer;
import com.asohofrucol.service.FormService;
import java.lang.IllegalAccessException;
import java.lang.IllegalArgumentException;

import java.lang.reflect.Field;

@Component
public class FormServiceImpl implements FormService {
	@Autowired
	private FormFieldDataDao formFieldDataDao;

	@Autowired
	private FormFieldInputDao formFieldInputDao;
	
	@Autowired
	private FormFieldInputAnswerDao formFieldInputAnswerDao;

	@Override
	public GenericFieldDTO getFormField(Long formFieldId) {
		GenericFieldDTO gFieldDto = new GenericFieldDTO();
		Class<? extends GenericFieldDTO> genericClass = gFieldDto.getClass();
		List<FormFieldData> formFieldDatas = formFieldDataDao
				.listByFormField(formFieldId);
		for (FormFieldData formFieldData : formFieldDatas) {
			System.out
					.println("name del dato = " + formFieldData.getDataName());
			for (Field field : genericClass.getDeclaredFields()) {
				if (formFieldData.getDataName().equalsIgnoreCase(
						field.getName())) {
					field.setAccessible(true);
					try {
						field.set(gFieldDto, formFieldData.getDataValue());
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				} else if (formFieldData.getDataName().equalsIgnoreCase("op")) {
					gFieldDto.getOptions().put(formFieldData.getDataValue(),
							formFieldData.getDataValueCode());
				}
			}

		}

		List<FormFieldInput> inputs = formFieldInputDao
				.listByFormField(formFieldId);
		if (!inputs.isEmpty()) {
			gFieldDto
					.setInput(FormFieldInputHelper.convertToDTO(inputs.get(0)));
		}
		return gFieldDto;
	}

	@Override
	public GenericFieldDTO getFormField(Long formFieldId, Long formAnswerId) {
		GenericFieldDTO genField = this.getFormField(formFieldId);
		List<FormFieldInputAnswer> answers = formFieldInputAnswerDao.listByFormFieldInputAndFormAnswer(genField.getInput().getId(), formAnswerId);
		genField.getInput().setValue(answers.get(0).getValue());
		genField.getInput().setFormAnswerId(answers.get(0).getFormAnswer().getId());
		return genField;
	}

}
